<template>
  <div>
    <el-card class="card" style="max-width: 1200px">
      <div>
        <div class="flex justify-between">
          <div class="mb-10px flex gap-10px">
            <div class="flex items-center">
              <span>章节号：</span>
              <el-input
                v-model="selectedSectionId"
                placeholder="请输入章节号"
                style="width: 150px; margin-left: 10px"
                type="number"
                :min="1"
                @change="handleSectionChange"
              />
            </div>
          </div>
          <div class="btn-area">
            <el-button style="margin-left: 10px">刷新</el-button>
            <el-button type="primary" @click="addTopic">新增</el-button>
          </div>
        </div>
        <el-table :data="topicList" border style="width: 100%">
          <el-table-column prop="title" label="题目" />
          <el-table-column prop="options" label="选项" />
          <el-table-column prop="answer" label="答案" />
          <el-table-column prop="analysis" label="解析" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="updateTopic">修改</el-button>
              <el-button type="danger" size="small" @click="deleteTopicById(scope.row.id)">
                删除
              </el-button>
              <el-upload
                class="handle"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              >
                <el-button type="primary" size="small">上传</el-button>
              </el-upload>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 新增题目 -->
      <el-dialog width="500">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          status-icon
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-form-item label="章节" prop="sectionId">
            <el-input v-model="ruleForm.sectionId" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="知识点号" prop="knowPointId">
            <el-input v-model="ruleForm.knowPointId" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="题目" prop="sectionName">
            <el-input v-model="ruleForm.sectionName" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="选项" prop="class">
            <el-input v-model="ruleForm.options" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="解析" prop="description">
            <el-input v-model="ruleForm.analysis" type="textarea" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button>取消</el-button>
            <el-button type="primary">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
    <el-dialog
      v-model="dialogVisible1"
      :title="handleTopic + '题目'"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="章节号" prop="name">
          <el-input v-model="ruleForm.sectionId" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="知识点号" prop="stuNum">
          <el-input v-model="ruleForm.knowPointId" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="题目" prop="title">
          <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="选项" prop="options">
          <el-input v-model="ruleForm.options" />
        </el-form-item>
        <el-form-item label="解析" prop="analysis">
          <el-input v-model="ruleForm.analysis" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getTopiclist, deleteTopic } from "@/api/test/test";

// 对话框状态设置
const dialogVisible1 = ref(false);

// 题目操作
const handleTopic = ref("新增");

// 打开对话框
const openDialog = (isAdd: boolean) => {
  if (isAdd) {
    handleTopic.value = "新增";
  } else {
    handleTopic.value = "修改";
  }
  dialogVisible1.value = true;
};

// 新增题目按钮触发
const addTopic = () => {
  openDialog(true);
};
// 修改题目按钮触发
const updateTopic = (row: any) => {
  currentRow = row;
  openDialog(false);
};

// 表单验证规则
const rules = reactive({
  sectionId: [{ required: true, message: "请输入章节号", trigger: "blur" }],
  knowPointId: [{ required: true, message: "请输入知识点号", trigger: "blur" }],
  title: [{ required: true, message: "请输入题目", trigger: "blur" }],
  options: [{ required: true, message: "请输入选项", trigger: "blur" }],
  analysis: [{ required: true, message: "请输入解析", trigger: "blur" }],
});

// 关闭对话框
const resetForm = () => {
  dialogVisible1.value = false;
};

const handleClose = async (done: () => void) => {
  await ElMessageBox.confirm("是否要关闭?");
  done();
};

const ruleFormRef = ref();

let currentRow = {
  name: "",
  class: "",
  id: "",
  tel: "",
  email: "",
};

// 提交表单逻辑
const submitForm = () => {
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (handleTopic.value === "新增") {
        topicList.push({
          id: currentRow.id,
          answer: ruleForm.answer,
          title: ruleForm.title,
          options: ruleForm.options,
          analysis: ruleForm.analysis,
        });
        dialogVisible1.value = false;
        ElMessage.success("新增成功");
      } else {
        handleTopic.value = "修改";
        const index = topicList.findIndex((item) => item.id === currentRow.id);
        if (index !== -1) {
          topicList[index].title = ruleForm.title;
          topicList[index].options = ruleForm.options;
          topicList[index].analysis = ruleForm.analysis;
        }
        dialogVisible1.value = false;
        ElMessage.success("修改成功");
      }
    } else {
      ElMessage.error("填写内容不合法");
    }
  });
};

interface topicInfo {
  id: string;
  title: string;
  options: string;
  answer: string;
  analysis: string;
}

// 获取题目章节号
const selectedSectionId = ref(1);

// 使用 reactive 管理响应式列表
const topicList = reactive<topicInfo[]>([]);

// 获取题目数据
const handleGetTopic = async () => {
  try {
    const res = await getTopiclist(selectedSectionId.value);
    // 清空原有数据并重新填充
    topicList.splice(0, topicList.length);
    res.forEach((item: any) => {
      topicList.push({
        id: item.id,
        title: item.question.title,
        answer: item.question.answer,
        options: item.question.options
          ? item.question.options.map((opt: any) => `${opt.key}: ${opt.value}`).join(" | ")
          : "",
        analysis: item.question.analysis,
      });
    });
  } catch (error) {
    console.error("获取题目失败:", error);
  }
};
// 切换题目章节
const handleSectionChange = () => {
  handleGetTopic();
};
// 删除题目
const deleteTopicById = async (topicId: string) => {
  await deleteTopic(topicId);
  handleGetTopic();
  ElMessage.success("删除成功");
};
// 表单绑定数据
const ruleForm = reactive({
  sectionId: "",
  sectionName: "",
  knowPointId: "",
  answer: "",
  title: "",
  options: "",
  analysis: "",
});

onMounted(() => {
  handleGetTopic();
});
</script>
<style>
.card {
  margin: 20px;
}
.btn-area {
  margin-bottom: 10px;
  float: right;
}
.handle {
  display: inline-block;
  width: 30%;
  margin: 3px;
}
.el-table__header,
.el-table__body {
  table-layout: fixed;
}
.el-button {
  margin-left: 0;
  margin-right: 5px;
}

.el-table th,
.el-table td {
  width: 25%;
}
</style>
